<?php

namespace App\Console\Commands\Tools\Camera;

use App\Kuafu\Shop\Enum\CodeEnum;
use App\Kuafu\Shop\Model\CameraModel;
use App\Kuafu\Shop\Model\ShopMonitorDataHourModel;
use App\Kuafu\Shop\Model\ShopMonitorDataModel;
use App\Kuafu\Shop\Service\ShopService;
use App\Library\FeiShu\SendFs;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Kuafu\GeneralFs\BuildFs;

class CheckShopMonitorData extends Command
{
    protected $signature   = 'tools:check-shop-monitor-data';
    protected $description = '校验昨日客流是否异常';

    protected string $notifyNormalText = '';
    protected string $notifyErrorText  = '';

    public function handle()
    {
//        $shopList = $this->getCameraShopList();
////        $shopList = [
////            13689,
////            13682,
////            14502
////        ];
//        foreach ($shopList as $shopId) {
//            $this->checkLastDaysData($shopId);
//        }
//
//        $this->sendFs();

    }

    private function getCameraShopList(): Collection
    {
        $list = CameraModel::query()
                           ->where('type', CodeEnum::SHOP_CAMERA_TYPE_1)
                           ->get()
                           ->pluck('shopId')
                           ->unique()
                           ->values();

        return $list;
    }

    private function checkLastDaysData(int $shopId, int $days = 1)
    {
        $sevenDaysAgoStartingTimestamp = Carbon::yesterday()->subDays($days)->startOfDay()->getTimestamp();
        $yesterdayEndingTimestamp      = Carbon::yesterday()->subDays($days)->endOfDay()->getTimestamp();


        $shopInfo = ShopService::getShopInfo($shopId);
        if ($shopInfo->status != CodeEnum::SHOP_STATUS_NORMAL) {
            // 门店非正常状态 不记录
            return;
        }
        // 判断门店第一次客流的数据时间
        $firstDataDate = ShopMonitorDataHourModel::query()
                                                 ->from(DB::raw('kf_shop_monitor_data_hour FORCE INDEX (idx_shopTypeAt)'))
                                                 ->where('shopId', $shopId)
                                                 ->whereIn('type', [
                                                     ShopMonitorDataModel::TYPE_IN_SHOP,
                                                     ShopMonitorDataModel::TYPE_PASS_SHOP,
                                                 ])
                                                 ->orderBy('dataAt')
                                                 ->first();


        if (empty($firstDataDate) || time() - $firstDataDate->dataAt < 87600 * $days) {
            // 未满 x 天
            $this->notifyNormalText .= vsprintf("%s(%s) 门店客流未满 %s 天" . PHP_EOL, [
                $shopInfo->name,
                $shopInfo->shopCode,
                $days
            ]);

        } else {
            $total = ShopMonitorDataHourModel::query()
                                             ->from(DB::raw('kf_shop_monitor_data_hour FORCE INDEX (idx_shopTypeAt)'))
                                             ->where('shopId', $shopId)
                                             ->whereIn('type', [
                                                 ShopMonitorDataModel::TYPE_IN_SHOP,
                                                 ShopMonitorDataModel::TYPE_PASS_SHOP,
                                             ])
                                             ->whereBetween('dataAt',
                                                 [$sevenDaysAgoStartingTimestamp, $yesterdayEndingTimestamp])
                                             ->selectRaw("count(1) as countAll, sum(count) as sumAll")
                                             ->first();


            // 历史日均客流
            $avgSum = (int)($total->sumAll / $days);

            // 历史日均客流为 0, 已作废不记录
            if (empty($avgSum)) {
                return;
            }

            // 昨日客流
            $yesterdayTotal    = ShopMonitorDataHourModel::query()
                                                         ->from(DB::raw('kf_shop_monitor_data_hour FORCE INDEX (idx_shopTypeAt)'))
                                                         ->where('shopId', $shopId)
                                                         ->whereIn('type', [
                                                             ShopMonitorDataModel::TYPE_IN_SHOP,
                                                             ShopMonitorDataModel::TYPE_PASS_SHOP,
                                                         ])
                                                         ->whereBetween('dataAt',
                                                             [
                                                                 Carbon::yesterday()->startOfDay()->getTimestamp(),
                                                                 Carbon::yesterday()->endOfDay()->getTimestamp()
                                                             ])
                                                         ->selectRaw("count(1) as countAll, sum(count) as sumAll")
                                                         ->first();
            $yesterdayTotalSum = $yesterdayTotal->sumAll ?? 0;

//            dd($yesterdayTotalSum, bcdiv($yesterdayTotalSum, $avgSum, 2));
//            try {
            // 数据比是否小于 50%
            if (bccomp(bcdiv($yesterdayTotalSum, $avgSum, 2), 0.4, 2) <= 0) {
                // 说明名店数据异常
                $this->notifyErrorText .= vsprintf("%s[%s] 昨日客流 %s, 同比上周下降 %s 人次(总 %s ), 标记异常且需要关注 " . PHP_EOL,
                    [
                        $shopInfo->name,
                        $shopInfo->shopCode,
                        $yesterdayTotalSum,
                        $avgSum - $yesterdayTotalSum,
                        $avgSum
                    ]);

            } else {
                // 门店数据正常
            }
//            } catch (\Exception $exception) {
//                dd($yesterdayTotalSum, $avgSum);
//            }

        }
    }

    private function sendFs()
    {
//        if (!empty($this->notifyNormalText)) {
//            BuildFs::newRobot(SendFs::ROBOT_SHOP_CAMERA_DATA_STATUS)
//                   ->setTitleContent('客流数据为满足检测门店', $this->notifyNormalText)
//                   ->send();
//        }

//        dd($this->notifyErrorText);
        if (!empty($this->notifyErrorText)) {
            BuildFs::newRobot(SendFs::ROBOT_SHOP_CAMERA_DATA_STATUS)
                   ->setTitleContent('客流异常门店通知', $this->notifyErrorText)
                   ->send();
        }
    }
}
